<template>
  <div id="login-content">
    <h1>登录界面</h1>
    <Form ref="formInline" :model="formInline" :rules="ruleInline" class="login-form" @keydown.enter.native="handleSubmit('formInline')">
      <Form-item prop="username">
        <Input type="text" v-model.trim="formInline.username" placeholder="请输入用户名">
          <Icon type="ios-person-outline" slot="prepend"></Icon>
        </Input>
      </Form-item>
      <Form-item prop="password">
        <Input type="password" v-model.trim="formInline.password" placeholder="请输入密码">
          <Icon type="ios-lock-outline" slot="prepend"></Icon>
        </Input>
      </Form-item>
      <Form-item>
        <Button class="login-btn" type="primary" @click="handleSubmit('formInline')" long>登录</Button>
      </Form-item>
    </Form>
  </div>
</template>
<script>
export default {
  data () {
    return {
      formInline: {
        username: '',
        password: ''
      },
      // 表单数据前端验证
      ruleInline: {
        username: [
          { required: true, message: '请填写用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请填写密码', trigger: 'blur' },
          { type: 'string', min: 3, message: '密码长度不能小于3位', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          // ajax 请求
          this.$postRequest('/user/login/', this.formInline).then(response => {
            // 如果存在正确响应，则存储login返回的token
            if (response) {
              localStorage.setItem('user_info', JSON.stringify(response.data))
              this.$Message.success('登录成功!')
              this.$router.push('/dashboar')
            }
          }).catch( error => {
            console.log(error)
          })
        } else {
          this.$Message.error('表单验证失败!')
        }
      })
    }
  }
}
</script>

<style scoped>
  #login-content{
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    align-items: center;
    justify-content: center;
    height: 70%;
  }
  #login-content h1{
    color: white;
    font-size: 50px;
    margin-bottom: 50px;
  }
  .login-form{
    width: 300px;
  }
</style>